package com.buer.service.util;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ObjectUtil {
    private static final Logger logger = LoggerFactory.getLogger(ObjectUtil.class);

    /**
     * 将javabean转为map类型，然后返回一个map类型的值
     * @param obj
     * @return
     */
    public static Map<String, Object> bean2Map(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>();
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    Object val = propertyUtilsBean.getNestedProperty(obj, name);
                    // 要是对应的值是一个List，则将List中元素循环为一个List<Map<String, Object>>
                    if (val instanceof List) {
                        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                        for (Object o : (List) val) {
                            list.add(bean2Map(o));
                        }
                        params.put(name, list);
                    } else {
                        params.put(name, val);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return params;
    }

    /**
     * Map转bean
     * @param map
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> T map2bean(Map<String, Object> map, Class<T> beanClass) {
        try {
            if (map == null)
                return null;

            T obj = beanClass.newInstance();

            Field[] fields = beanClass.getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }

                field.setAccessible(true);
                if (map.containsKey(field.getName())){
                    field.set(obj, map.get(field.getName()));
                }
            }

            return obj;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }

    }

}
